<template>
  <div class="top_search">
    <a-form layout="vertical" :model="searchForm" style="display: flex">
      <a-form-item label="交易类型" class="form_item">
        <a-cascader
          :changeOnSelect="true"
          @change="handleCascaderChange"
          v-model:value="transitionValue"
          :options="transitionType"
          placeholder="请选择"
          allowClear
        />
      </a-form-item>
      <a-form-item label="业务单号" class="form_item">
        <a-input
          placeholder="请输入"
          v-model:value="searchForm.bill_no"
          allowClear
        />
      </a-form-item>
      <a-form-item label="交易时间" style="width: 300px" class="form_item">
        <a-range-picker
          @change="handleDateChange"
          v-model:value="timeRange"
          allowClear
        />
      </a-form-item>
      <a-form-item label="余额类型" class="form_item">
        <a-select
          v-model:value="searchForm.account_type"
          placeholder="请选择"
          :options="balanceType"
          allowClear
        ></a-select>
      </a-form-item>
      <a-form-item label="关联项目" class="form_item">
        <a-select
          placeholder="请输入"
          style="width: 200px"
          :value="searchForm.merchant_library_id"
          @change="handleChange"
          allowClear
        >
          <a-select-option
            v-for="(item, index) in libraryList"
            :key="index"
            :value="String(item.id)"
            :option="item"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>

      <!-- <a-form-item style="width: 200px">
        <a-space>
          <a-button type="primary" @click="queryThis('query')">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button
            type="default"
            style="margin-left: 10px"
            @click="queryThis('reset')"
          >
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
          <a-button type="primary" @click="handleExport">导出</a-button>
        </a-space>
      </a-form-item> -->
      <a-form-item label=" " style="flex: 1; margin-left: 10px; display: flex">
        <a-button type="primary" @click="queryThis('query')">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button
          type="default"
          style="margin-left: 10px"
          @click="queryThis('reset')"
        >
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
        <a-button
          type="primary"
          :loading="exportLoading"
          @click="handleExport"
          style="margin-left: 10px"
          ><template #icon> <ReloadOutlined /> </template>导出</a-button
        >
      </a-form-item>
    </a-form>
  </div>

  <div class="table_con">
    <a-table
      :loading="tableLoading"
      :pagination="pagination"
      :dataSource="dataSource"
      :columns="columns"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'account_type'">
          <a-space direction="vertical">
            <span>
              {{ record.module_event }}
            </span>
            <span style="color: #999">
              {{ record.account_type }}
            </span>
          </a-space>
        </template>
        <template v-if="column.key === 'changes'">
          {{ record.changes }} {{ record.unit }}
        </template>
        <template v-if="column.key === 'modification'">
          <div>交易前：{{ record.pre_balance }} {{ record.unit }}</div>
          <div>交易后：{{ record.balance }} {{ record.unit }}</div>
        </template>

        <template v-if="column.key === 'title'">
          <a-tooltip placement="top">
            <template #title>
              <span>{{ record.title }}</span>
            </template>
            <div >
              {{ record.title }}
            </div>
          </a-tooltip>
        </template>
      </template>
    </a-table>
  </div>

  <ExportMdal :visible="visibleExport" @cacel="visibleExport = false" />
</template>

<script>
import { defineComponent, reactive, toRefs, computed } from "vue";
import {
  DownOutlined,
  UpOutlined,
  SearchOutlined,
  ReloadOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";
import request from "../../../../common/utils/request";
import { message } from "ant-design-vue";
import ExportMdal from "../../../shotstack/components/ExportMdal/index.vue";

const initialParams = {
  /**
   * 余额类型
   */
  account_type: null,
  /**
   * 业务单号
   */
  bill_no: "",
  /**
   * 项目id
   */
  merchant_library_id: null,
  /**
   * 交易类型
   */
  module_event: [],
  /**
   * 交易时间-开始
   */
  start_time: "",
  /**
   * 交易时间-结束
   */
  end_time: "",
};
export default defineComponent({
  name: "transactionFlow",
  components: {
    DownOutlined,
    UpOutlined,
    SearchOutlined,
    ReloadOutlined,
    ExportMdal,
  },
  setup() {
    const state = reactive({
      transitionValue: [],
      libraryList: [],
      tableLoading: false,
      dataSource: [],
      timeRange: null,
      pageInfo: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      searchForm: {
        ...initialParams,
      },
      transitionType: [],
      balanceType: [],
      visibleExport: false,
      columns: [
        {
          title: "类型",
          dataIndex: "account_type",
          key: "account_type",
        },
        {
          title: "交易名称",
          dataIndex: "title",
          key: "title",
        },
        {
          title: "项目名称",
          dataIndex: "merchant_name",
          key: "merchant_name",
        },
        {
          title: "业务单号",
          dataIndex: "bill_no",
          key: "bill_no",
        },
        {
          title: "数量",
          dataIndex: "changes",
          key: "changes",
        },
        {
          title: "变动情况",
          dataIndex: "modification",
          key: "modification",
        },
        {
          title: "交易时间",
          dataIndex: "created_at",
          key: "created_at",
        },
      ],
      exportLoading: false,
    });

    const pagination = computed(() => ({
          current: state.pageInfo.page,
          total: state.pageInfo.total,
          pageSize: state.pageInfo.pageSize,
          showSizeChanger: true,
          showTotal: (total) => `共${total}条`,
        }));

    const handleExport = () => {
      state.exportLoading = true;
      request
        .put("/work_ai", "/user/shotstack/user/billing/export", {
          ...state.searchForm,
        })
        .then((res) => {
          if (res.result) {
            state.exportLoading = false;
            state.visibleExport = true;
          }
        })
        .catch((err) => {
          state.exportLoading = false;
          message.error("操作失败");
        })
        .finally(() => {
          state.exportLoading = false;
        });
    };

    const handleTableChange = ({ current, pageSize }) => {
      console.log(current, pageSize);
      state.pageInfo.pageSize = pageSize;
      state.pageInfo.page = current;
      getTableList();
    };

    const handleDateChange = (date, dateString) => {
      state.searchForm.start_time = dateString[0];
      state.searchForm.end_time = dateString[1];
    };

    const handleChange = (val) => {
      state.searchForm.merchant_library_id = val;
    };

    const handleCascaderChange = (val) => {
      state.transitionValue = val;
      let arr = [];
      if (val?.length == 1) {
        arr = state.transitionType
          .find((item) => item?.value == val[0])
          ?.children?.map((item) => item?.value);
      } else if (val?.length == 2) {
        arr = [val[1]];
      }
      if (val) {
        state.searchForm.module_event = arr;
      } else {
        state.searchForm.module_event = [];
      }
    };

    const getTableList = () => {
      let params = {};
      state.tableLoading = true;
      Object.assign(params, state.pageInfo);
      Object.assign(params, state.searchForm);
      state.transitionType = [];
      state.balanceType = [];
      request
        .get("/work_ai", "/user/shotstack/user/billing/list", params)
        .then((res) => {
          state.dataSource = res.result.data;
          state.pageInfo.total = res?.result?.total;
          for (let key in res.result.account_type_list) {
            state.balanceType.push({
              label: res.result.account_type_list[key],
              value: key,
            });
          }
          res?.result?.event_list?.map((item) => {
            let obj = {};
            obj.value = item?.key;
            obj.label = item?.title;
            obj.children = [];
            item?.item?.map((second_item) => {
              obj.children.push({
                label: second_item?.title,
                value: second_item?.key,
              });
            });
            state.transitionType.push(obj);
          });
          state.tableLoading = false;
        })
        .catch((err) => {
          state.tableLoading = false;
        });
    };

    const queryThis = (type) => {
      Object.assign(state.pageInfo,{
        page: 1,
        pageSize: 10,
        total: 0,
      })

      if (type == "query") {
        getTableList();
      } else {
        state.searchForm = {
          ...initialParams,
        };
        state.timeRange = null;
        getTableList();
      }
    };

    const getLibraryList = () => {
      let params = {
        page: 1,
        pageSize: 100,
      };
      request
        .get("/work_ai", "/user/shotstack/library/withGroup/list", params)
        .then((res) => {
          state.libraryList = res.result;
        });
    };

    getTableList();
    getLibraryList();

    return {
      ...toRefs(state),
      pagination,
      handleTableChange,
      getTableList,
      queryThis,
      handleDateChange,
      handleChange,
      handleExport,
      handleCascaderChange,
    };
  },
});
</script>

<style lang="less" scoped>
.form_item {
  margin-left: 10px;
  width: 200px;

  &:nth-child(1) {
    margin-left: 0;
  }
}

.export {
  text-align: right;
  margin-bottom: 10px;
}

.w-20 {
  width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
